<?php

namespace Home\Controller;

class VoteController extends HomeCommonController
{
    const VOTE_COUNT = 10;

    /**
     * 种子选手列表
     *
     * http://127.0.0.1:8093/index.php?s=/Vote/seedList/match_id/1
     */
    public function seedList()
    {
        $match_id  = I('match_id');
        // 按照得票顺序排队
        $where = array('match_id' => $match_id);
        $list = M('seed')->where($where)->select();
//        echo M('seed s')->getLastSql(); exit;
        foreach ($list as $key => $val) {
            $list[$key]['vote_count'] = M('vote')->where(array('seed_id' => $val['id']))->count();
            $list[$key]['photo_url'] = showImage($val['photo_url']);
        }

        $this->assign('voto_list', $list);
        $this->display();

    }

    /**
     * 投票
     *
     * http://127.0.0.1:8093/index.php?s=/Vote/vote
     */
    public function vote()
    {
        $member_id = I('member_id');
        $match_id  = I('match_id');
        $seed_id   = I('seed_id');
        if (!$member_id || !$match_id || !$seed_id) {
            $this->showMessage(array(), self::ERROR_CODE, '参数错误');
        }

        // 每个人每场比赛只能投10票
        $model = M('vote');
        $where = array(
            'member_id' => $member_id,
            'match_id' => $match_id
        );
        $count = $model->where($where)->count();
        if ($count > self::VOTE_COUNT) {
            $this->showMessage(array(), self::ERROR_CODE, '每个人每场比赛只能投10票');
        }
        $data = array(
            'member_id' => $member_id,
            'match_id' => $match_id,
            'seed_id' => $seed_id,
            'create_time' => NOW_TIME
        );
        $res = $model->add($data);
        if ($res) {
            $this->showMessage();
        } else {
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }
}